package com.wiseman.writing.utility;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.os.Environment;
import android.util.Log;


public class BSJniApi{
	
	static {
		System.loadLibrary("writing");
	}
	
	static BSJniApi s_Instance = null;
	
	private BSJniApi(){
		
	};
	
	public static BSJniApi createBSJniApi(Context context, int runmode, int codepage){
		
		if(s_Instance == null){
			
			s_Instance = new BSJniApi();
			
			if(s_Instance.loadFromAssets(context, runmode,  codepage) == null){
				Log.i("stroke order", "open stroke data error!");
			}
		}
		
		return s_Instance;				
	}
		
	public String loadFormSd(String path, int runMode, int codePage) {
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			File file = new File(path);
			if (file.exists()) {
				try {
					@SuppressWarnings("resource")
					FileInputStream in = new FileInputStream(file);
					return load(in.getFD(), 0, runMode, codePage);				
				} catch (IOException e) {
					e.printStackTrace();
				}

			} else {
				Log.d("file", "can't find file!");
			}
		}
		return null;
	}

	// ����jni
	public String loadFromAssets(Context context, int runMode, int codePage) {				
		String ret = null;	
		
		try {
			AssetFileDescriptor rd = context.getAssets().openFd("writing.mp3");
			if (rd != null) {
				FileDescriptor fd = rd.getFileDescriptor();
				long offset = rd.getStartOffset();
				ret = load(fd, offset, runMode, codePage);
			}			

		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return ret;	
	}	
	

	// ����jni
	public String loadFromAssets(Context context, String path) {				
		String ret = null;	
		
		try {
			AssetFileDescriptor rd = context.getAssets().openFd(path);
			if (rd != null) {
				FileDescriptor fd = rd.getFileDescriptor();
				long offset = rd.getStartOffset();
			//	ret = loadFile(fd, offset);
			}			

		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return ret;	
	}	
		
	public native String load(FileDescriptor fd, long offset, int runMode, int codePage);
	public native int prepareData(char code);
	public native int getStrokeNum();
	public native int[] getDrawPoint(int fontSize);
	public native int[] getFlagTab();
	public native void unLoad();
	public native int getLanguage(); 
}
